package com.ymy.thinking.in.spring.dependency.injection;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;

/**
 * Api 方式的依赖注入
 *
 * @author Ringo
 * @date 2021/9/29 17:04
 */
public class ApiDependencySetterInjectionDemo {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(ApiDependencySetterInjectionDemo.class);

        applicationContext.registerBeanDefinition("user", createUserBeanDefinition());
        applicationContext.registerBeanDefinition("userHolder", createUserHolderBeanDefinition());

        System.out.println(applicationContext.getBeansOfType(User.class));

        UserHolder userHolder = applicationContext.getBean(UserHolder.class);
        System.out.println(userHolder);
    }

    // Java 注解方式注册 Bean
    @Bean
    public User user1() {
        return new User("刘德华", 18);
    }

    // Api: 创建 User 的 BeanDefinition
    private static BeanDefinition createUserBeanDefinition() {
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(User.class)
                .addPropertyValue("name", "张三丰")
                .addPropertyValue("age", 18)
                .setPrimary(true);
        return builder.getBeanDefinition();
    }

    // Api: 创建 UserHolder 的 BeanDefinition
    private static BeanDefinition createUserHolderBeanDefinition() {
        BeanDefinitionBuilder builder = BeanDefinitionBuilder
                .genericBeanDefinition(UserHolder.class)
                .addPropertyReference("user", "user");
//                .setAutowireMode(AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE);

        return builder.getBeanDefinition();
    }
}
